package com.atguigu.guli.service.cms.controller.api;


import com.atguigu.guli.service.base.result.R;
import com.atguigu.guli.service.cms.service.AdService;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 广告推荐 前端控制器
 * </p>
 *
 * @author atguigu
 * @since 2021-06-01
 */
@RestController

@RequestMapping("/api/cms/ad")
public class ApiAdController {
    //操作redis，可以将任意类型数据序列化(二进制字符串)后存入到redis中
    /*
        redis整合后，由于当前环境中引入的依赖包含了redisAutoConfiguration自动配置类所依赖的类，所以
        redis的模板类对象会自动创建注入到容器中
     */
    // redis: 底层存的都是字符串
    //RedisTemplate默认使用序列化的方式存数据到redis中，如果数据没有实现序列化接口则报错
    //解决：我们可以修改RedisTemplate 的序列化方式
    @Autowired
    RedisTemplate redisTemplate;
    //将字符串类型存入redis
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @GetMapping("set")
    public R set(){
        redisTemplate.opsForValue().set("rtKey" , "rtVal" , 100 , TimeUnit.SECONDS);
        stringRedisTemplate.opsForValue().set("srT" , "srtVal" , 100 , TimeUnit.SECONDS);

       redisTemplate.opsForValue().set("rtObjKey" , R.ok());

        Gson gson = new Gson();
        //将对象转为json字符串存入到redis中
        stringRedisTemplate.opsForValue().set("srtObjKey" , gson.toJson(R.ok()));

        return R.ok();
    }
    @GetMapping("get")
    public R get(){
        Long expire = redisTemplate.getExpire("rtKey", TimeUnit.SECONDS);
        System.out.println("expire = " + expire);
        Object rtKey = redisTemplate.opsForValue().get("rtKey");
        System.out.println("rtKey = " + rtKey);
        Boolean hasKey = stringRedisTemplate.hasKey("srT");
        if(hasKey){
            String srT = stringRedisTemplate.opsForValue().get("srT");
            System.out.println("srT = " + srT);
        }

        R rtObjKey = (R) redisTemplate.opsForValue().get("rtObjKey");
        System.out.println("rtObjKey = " + rtObjKey);
        String srtObjKey = stringRedisTemplate.opsForValue().get("srtObjKey");
        Gson gson = new Gson();
        R r = gson.fromJson(srtObjKey, R.class);
        System.out.println("r = " + r);


        return R.ok();
    }
    //查询所有的广告：将广告分类存放后交给前端
    /*
        Map map
            map.put("banners" , bannerlist);
            map.put("courses" , courselist);
            map.put("teachers" , teacherlist);
     */
    @Autowired
    AdService adService;
    @GetMapping("listAds")
    public R listAds(){
        Map adsMap = adService.listAds();
        return R.ok().setData(adsMap);
    }
}

